{#
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

#}
{% extends "airflow/dag.html" %}

{% block title %}Airflow - DAGs{% endblock %}

{% block head_css %}
{{ super() }}
<link rel="stylesheet" type="text/css"
      href="{{ url_for('static', filename='css/graph.css') }}">
{% endblock %}

{% block content %}
{{ super() }}
    {% if doc_md %}
        <div class="rich_doc" style="margin-bottom: 15px;">{{ doc_md|safe }}</div>
    {% endif %}
    <div class="form-inline">
        <form method="get" style="float:left;">
            {{ state_token }}
            Base date: {{ form.base_date(class_="form-control") }}
            Number of runs: {{ form.num_runs(class_="form-control") }}
            Run:
            {{ form.execution_date(class_="form-control") | safe }}
            Layout:
            {{ form.arrange(class_="form-control") | safe }}
            <input type="hidden" name="root" value="{{ root }}">
            <input type="hidden" value="{{ dag.dag_id }}" name="dag_id">
            <input name="_csrf_token" type="hidden" value="{{ csrf_token() }}">
            <input type="submit" value="Go" class="btn btn-default"
            action="" method="get">
        </form>
            <div class="input-group" style="float: right;">
              <input type="text" id="searchbox" class="form-control" placeholder="Search for..." onenter="null">
            </div><!-- /input-group -->
        <div style="clear: both;"/>
    </div>
<hr/>
<div>
    {% for op in operators %}
    <div class="legend_item" style="border-width:1px;float:left;background:{{ op.ui_color }};color:{{ op.ui_fgcolor }};">
        {{ op.__name__ }}
    </div>
    {% endfor %}

    <div style"background-color: blue;">
    <div class="legend_item state" style="border-color:white;">no status</div>
    <div class="legend_item state" style="border-color:grey;">queued</div>
    <div class="legend_item state" style="border-color:gold;">retry</div>
    <div class="legend_item state" style="border-color:turquoise;">rescheduled</div>
    <div class="legend_item state" style="border-color:pink;">skipped</div>
    <div class="legend_item state" style="border-color:red;">failed</div>
    <div class="legend_item state" style="border-color:lime;">running</div>
    <div class="legend_item state" style="border-color:green;">success</div>
    </div>
    <div style="clear:both;"></div>
</div>
<div id="error" style="display: none; margin-top: 10px;" class="alert alert-danger" role="alert">
        <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
        <span id="error_msg">Oops.</span>
</div>
<hr style="margin-bottom: 0px;"/>
<button class="btn btn-default pull-right" id="refresh_button">
    <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>
</button>
<div id="svg_container">

    <svg width="{{ width }}" height="{{ height }}">
        <g id='dig' transform="translate(20,20)"/>
        <filter id="blur-effect-1">
        <feGaussianBlur stdDeviation="3" />
        </filter>
    </svg>
    <img id="loading" alt="spinner" src="{{ url_for('static', filename='loading.gif') }}">
</div>
<hr>
{% endblock %}

{% block tail %}
    {{ super() }}

    <script src="{{ url_for_asset('d3.min.js') }}"></script>
    <script src="{{ url_for_asset('dagre-d3.min.js') }}"></script>
    <script>

    var highlight_color = "#000000";
    var upstream_color = "#2020A0";
    var downstream_color = "#0000FF";
    var initialStrokeWidth = '3px';
    var highlightStrokeWidth = '5px';

    var nodes = {{ nodes|safe }};
    var edges = {{ edges|safe }};
    var execution_date = "{{ execution_date }}";
    var arrange = "{{ arrange }}";

    // Below variables are being used in dag.js
    var tasks = {{ tasks|safe }};
    var task_instances = {{ task_instances|safe }};
    var getTaskInstanceURL = "{{ url_for('Airflow.task_instances') }}" +
      "?dag_id=" + encodeURIComponent(dag_id) + "&execution_date=" +
      encodeURIComponent(execution_date);

    var duration = 500;
    var stateFocusMap = {
        'no status':false, 'failed':false, 'running':false,
        'queued': false, 'success': false};

    // Preparation of DagreD3 data structures
    var g = new dagreD3.graphlib.Graph().setGraph({
        nodesep: 15,
        ranksep: 15,
        rankdir: arrange,
      })
      .setDefaultEdgeLabel(function() { return { lineInterpolate: 'basis' } });

    // Set all nodes and styles
    nodes.forEach(function(node) {
      g.setNode(node.id, node.value)
    });

    // Set edges
    edges.forEach(function(edge) {
      g.setEdge(edge.u, edge.v)
    });

    var render = dagreD3.render(),
      svg = d3.select("svg"),
      innerSvg = d3.select("svg g");

    innerSvg.call(render, g);

    function setUpZoomSupport() {
      // Set up zoom support for Graph
      var zoom = d3.behavior.zoom().on("zoom", function() {
            innerSvg.attr("transform", "translate(" + d3.event.translate + ")" +
                                        "scale(" + d3.event.scale + ")");
          });
      svg.call(zoom);
    }

    // Centering the DAG on load (Not implemented yet)
    // https://github.com/dagrejs/dagre-d3/issues/245

    setUpZoomSupport();
    inject_node_ids(tasks);

    d3.selectAll("g.node").on("click", function(d){
        task = tasks[d];
        if (task.task_type == "SubDagOperator")
            call_modal(d, execution_date, true);
        else
            call_modal(d, execution_date);
    });


    function highlight_nodes(nodes, color) {
        nodes.forEach (function (nodeid) {
            my_node = d3.select('#' + nodeid).node().parentNode;
            d3.select(my_node).selectAll("rect").style("stroke", color) ;
        })
    }

    d3.selectAll("g.node").on("mouseover", function(d){
        d3.select(this).selectAll("rect").style("stroke", highlight_color) ;
        highlight_nodes(g.predecessors(d), upstream_color);
        highlight_nodes(g.successors(d), downstream_color)

    });

    d3.selectAll("g.node").on("mouseout", function(d){
        d3.select(this).selectAll("rect").style("stroke", null) ;
        highlight_nodes(g.predecessors(d), null)
        highlight_nodes(g.successors(d), null)
    });


    {% if blur %}
    d3.selectAll("text").attr("class", "blur");
    {% endif %}

    $("g.node").tooltip({
      html: true,
      container: "body",
    });

    d3.selectAll("div.legend_item.state")
        .style("cursor", "pointer")
        .on("mouseover", function(){
            if(!stateIsSet()){
                state = d3.select(this).text();
                focusState(state);
            }
        })
        .on("mouseout", function(){
            if(!stateIsSet()){
                clearFocus();
            }
        });

    d3.selectAll("div.legend_item.state")
        .on("click", function(){
            state = d3.select(this).text();
            color = d3.select(this).style("border-color");

            if (!stateFocusMap[state]){
                clearFocus();
                focusState(state, this, color);
                setFocusMap(state);

            } else {
                clearFocus();
                setFocusMap();
            }
        });

    d3.select("#searchbox").on("keyup", function(){
        var s = document.getElementById("searchbox").value;
        var match = null;

        if (stateIsSet){
            clearFocus();
            setFocusMap();
        }

        d3.selectAll("g.nodes g.node").filter(function(d, i){
            if (s==""){
                d3.select("g.edgePaths")
                    .transition().duration(duration)
                    .style("opacity", 1);
                d3.select(this)
                    .transition().duration(duration)
                    .style("opacity", 1)
                    .selectAll("rect")
                    .style("stroke-width", initialStrokeWidth);
            }
            else{
                d3.select("g.edgePaths")
                    .transition().duration(duration)
                    .style("opacity", 0.2);
                if (d.indexOf(s) > -1) {
                    if (!match)
                        match = this;
                    d3.select(this)
                        .transition().duration(duration)
                        .style("opacity", 1)
                        .selectAll("rect")
                        .style("stroke-width", highlightStrokeWidth);
                }
                else {
                    d3.select(this)
                        .transition()
                        .style("opacity", 0.2).duration(duration)
                        .selectAll("rect")
                        .style("stroke-width", initialStrokeWidth);
                }
            }
        });

        // This moves the matched node in the center of the graph area
        // ToDo: Should we keep this here as it has no added value
        // and does not fit the graph on small screens, and has to scroll
        if(match) {
            var transform = d3.transform(d3.select(match).attr("transform"));
            transform.translate = [
                -transform.translate[0] + 520,
                -(transform.translate[1] - 400)
            ];
            transform.scale = [1, 1];

            d3.select("g.zoom")
                .transition()
                .attr("transform", transform.toString());
            innerSvg.attr("transform", "translate(" + transform.translate + ")" +
                                        "scale(1)");
        }
    });


    // Injecting ids to be used for parent/child highlighting
    // Separated from update_node_states since it must work even
    // when there is no valid task instance available
    function inject_node_ids(tasks) {
        $.each(tasks, function(task_id, task) {
            $('tspan').filter(function(index) { return $(this).text() === task_id; })
                    .parent().parent().parent()
                    .attr("id", task_id);
        });
    }

    function clearFocus(){
        d3.selectAll("g.node")
            .transition(duration)
            .style("opacity", 1);
        d3.selectAll("g.node rect")
            .transition(duration)
            .style("stroke-width", initialStrokeWidth);
        d3.select("g.edgePaths")
            .transition().duration(duration)
            .style("opacity", 1);
        d3.selectAll("div.legend_item.state")
            .style("background-color", null);
    }

    function focusState(state, node, color){
        d3.selectAll("g.node")
            .transition(duration)
            .style("opacity", 0.2);
        d3.selectAll("g.node."+state)
            .transition(duration)
            .style("opacity", 1);
        d3.selectAll("g.node." + state + " rect")
            .transition(duration)
            .style("stroke-width", highlightStrokeWidth)
            .style("opacity", 1);
        d3.select("g.edgePaths")
            .transition().duration(duration)
            .style("opacity", 0.2);
        d3.select(node)
            .style("background-color", color);
    }

    function setFocusMap(state){
        for (var key in stateFocusMap){
                stateFocusMap[key] = false;
        }
        if(state != null){
            stateFocusMap[state] = true;
        }
    }

    function stateIsSet(){
        for (var key in stateFocusMap){
            if (stateFocusMap[key]){
                return true
            }
        }
        return false
    }
    </script>
    <script src="{{ url_for_asset('graph.js') }}"></script>


{% endblock %}
